package com.etc.order.frontend.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.etc.order.common.domain.User;
import com.etc.order.common.dto.SimpleDTO;
import com.etc.order.common.service.UserService;
import com.etc.order.frontend.filter.AuthFilter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
public class UserController {
    @Resource
    @Reference
    private UserService userService;

    @PostMapping("/user/address/update")
    @ResponseBody
    public SimpleDTO updateAddress(String address) {
        User user = (User) AuthFilter.getSession().getAttribute("userInfoFrontend");
        if (user != null) {
            user.setUserAddress(address);
            if (userService.update(user, "address") > 0) {
                return new SimpleDTO(0, "成功", null);
            }
        }
        return new SimpleDTO(1, "失败", null);
    }

    @PostMapping("/user/username/update")
    @ResponseBody
    public SimpleDTO updateUsername(String username) {
        User user = (User) AuthFilter.getSession().getAttribute("userInfoFrontend");
        if (userService.findByUsername(username) != null) {
            return new SimpleDTO(1, "用户名已被使用", null);
        }
        if (user != null) {
            user.setUserName(username);
            if (userService.update(user, "username") > 0) {
                return new SimpleDTO(0, "成功", null);
            }
        }
        return new SimpleDTO(1, "失败", null);
    }

    @PostMapping("/user/phone/update")
    @ResponseBody
    public SimpleDTO updatePhone(String phone) {
        User user = (User) AuthFilter.getSession().getAttribute("userInfoFrontend");
        if (user != null) {
            user.setUserPhone(phone);
            if (userService.update(user, "phone") > 0) {
                return new SimpleDTO(0, "成功", null);
            }
        }
        return new SimpleDTO(1, "失败", null);
    }

    @PostMapping("/user/password/update")
    @ResponseBody
    public SimpleDTO updatePassword(String oldPassword, String newPassword) {
        User user = (User) AuthFilter.getSession().getAttribute("userInfoFrontend");
        if (user != null) {
            if (user.getUserPassword().equals(oldPassword)) {
                user.setUserPassword(newPassword);
                if (userService.update(user, "password") > 0) {
                    return new SimpleDTO(0, "成功", null);
                }
            } else {
                return new SimpleDTO(1, "旧密码不正确", null);
            }
        }
        return new SimpleDTO(1, "失败", null);
    }
}
